package com.zzzyh.forumsystemclient.cotroller;

import com.alibaba.fastjson.JSON;
import com.zzzyh.forumsystemclient.common.AppResult;
import com.zzzyh.forumsystemclient.common.Constant;
import com.zzzyh.forumsystemclient.common.ResultCode;
import com.zzzyh.forumsystemclient.model.LoginUser;
import com.zzzyh.forumsystemclient.model.Role;
import com.zzzyh.forumsystemclient.model.User;
import com.zzzyh.forumsystemclient.model.User_Role;
import com.zzzyh.forumsystemclient.services.IRoleService;
import com.zzzyh.forumsystemclient.services.ITokenBlacklistService;
import com.zzzyh.forumsystemclient.services.IUserService;
import com.zzzyh.forumsystemclient.services.IUser_RoleServices;
import com.zzzyh.forumsystemclient.utils.JwtUtils;
import com.zzzyh.forumsystemclient.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 郑雨杭
 * @create 2025/5/28 - 15:44
 */
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IRoleService roleService;
    @Autowired
    private IUser_RoleServices user_roleServices;
    @Autowired
    private ITokenBlacklistService tokenBlacklistService;


    // 创建普通用户
    @PostMapping("/createUser")
    @ApiOperation("创建普通用户")
    public AppResult createUser(@RequestBody User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        String nickname = user.getNickname();
        log.info("创建普通用户");
        log.info("用户名：{}", username);
        log.info("密码：{}", password);
        log.info("昵称：{}", nickname);

        if(StringUtil.isEmpty(username) || StringUtil.isEmpty(password)
                 || StringUtil.isEmpty(nickname)) {
            log.warn(ResultCode.FAILED_PARAM_ERROR.getMessage());
            return AppResult.failed(ResultCode.FAILED_PARAM_ERROR);
        }
        Role role = roleService.selectByName(Constant.USER_USER);
        user.setRole(role);
        userService.createUser(user);
        User_Role userRole = new User_Role();
        log.info("角色id{}" , role);
        log.info("用户id{}" , user.getId());
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        user_roleServices.createUser_Role(userRole);
        return AppResult.success(ResultCode.SUCCESS_USER_CREATE);
    }

    @RequestMapping("/login")
    public AppResult<String> login(@RequestBody User user){
        user.setSalt(userService.selectSaltByUsername(user.getUsername()));
        String jwt = userService.login(user);
        return AppResult.success("登录成功",jwt);
    }

    @RequestMapping("/logout")
    public AppResult<String> logout(@RequestHeader("Authorization") String token){
        tokenBlacklistService.addToBlacklist(token);
        return AppResult.success("退出成功");
    }

    @RequestMapping("/getUserInfo")
    public AppResult<User> getUserInfo(@RequestHeader("Authorization") String token){
        String userString = JwtUtils.getSubjectFromToken(token);
        LoginUser user = JSON.parseObject(userString, LoginUser.class);
        return AppResult.success(user.getUser());
    }

    @RequestMapping("/getUserInfoByUserId")
    public AppResult<User> getUserInfoByUserId(@RequestParam("userId") Long userId){
        User user = userService.selectUserByUserId(userId);
        user.setPassword(null);
        user.setSalt(null);
        return AppResult.success(user);
    }

    @RequestMapping("/updateUser")
    public AppResult<Void> updateUser(@RequestBody User user,@RequestHeader("Authorization") String token){
        String userString = JwtUtils.getSubjectFromToken(token);
        User loginUser = JSON.parseObject(userString, LoginUser.class).getUser();
        if(loginUser.getId() == null)
            return AppResult.failed(ResultCode.FAILED_UNAUTHORIZED);
        user.setId(loginUser.getId());
        log.info("user:{}",user);
        userService.updateUser(user);
        return AppResult.success();
    }
}
